package recursion

import problem.Problem

class Q344ReverseString extends Problem {
  def reverseString(s: Array[Char]): Unit = {
    if (s.length == 0 || s.length == 1) {}
    else if (s.length % 2 == 1) {
      reverse(s, s.length / 2 - 1, s.length / 2 + 1)
    } else {
      reverse(s, s.length / 2 - 1, s.length / 2)
    }
  }

  def reverse(a: Array[Char], i: Int, j: Int): Unit = {
    if (i >= 0) {
      val t = a(i)
      a(i) = a(j)
      a(j) = t
      reverse(a, i - 1, j + 1)
    }
  }

  override def test(): Unit = {
    val s0 = "hello".toArray
    reverseString(s0)
    s0.mkString("") shouldBe "hello".reverse

    val s1 = "hell".toArray
    reverseString(s1)
    s1.mkString("") shouldBe "hell".reverse
  }
}